<template>
  <el-dialog :model-value="dialogVisible" destroy-on-close>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">
        确定
      </el-button>
    </template>
    <div class="box">
      <div class="crop">
        <div class="cropper">
          <VueCropper
              ref="cropper"
              :img="imageDataUrl"
              :outputSize="option.size"
              :outputType="option.outputType"
              :autoCrop="option.autoCrop"
              :fixedBox="false"
              :autoCropWidth="option.autoCropWidth"
              :autoCropHeight="option.autoCropHeight"
              :full="option.full"
              @realTime="realTime"
          />
        </div>
        <div class="view">
          <div :class="{ 'img-preview': true, radian }" v-html="previewHtml"></div>
          <div class="btn">
            <div class="item" title="下载截图" @click="DownImg">
              <el-icon>
                <Download />
              </el-icon>
            </div>
          </div>
        </div>
      </div>
      <div class="tool">
        <el-button type="primary" @click="correct">矫正</el-button>
        <el-button type="primary" @click="rotateLeft">左旋</el-button>
        <el-button type="primary" @click="rotateRight">右旋</el-button>
        <el-button type="primary" @click="arcChange">弧度</el-button>
      </div>
      <input type="file" accept="image/*" @change="onFileChange" style="width: 70px; margin-left: 10px"/>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { Back, Download } from '@element-plus/icons-vue';
import {defineProps, ref, type Ref, watch} from 'vue';
import 'vue-cropper/dist/index.css';
import { VueCropper } from 'vue-cropper';

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  img: {
    type: String
  }
});


// 定义更新 props 的事件，用于 v-model 的双向绑定
const emit = defineEmits(["changeDialogVisible", "changeSubmitImg"]);

// const $emit = defineEmits(['cropClose']);
const cropper: any = ref(null);
const imageDataUrl = ref<string | null>(null);

const option = ref({
  size: 1,
  outputType: 'jpg',
  autoCrop: true,
  fixedNumber: [1, 1],
  autoCropWidth: 128,
  autoCropHeight: 128,
  full: true,
});


watch(() => props.img, (value) => {
  // imageDataUrl.value.time = []
  // form.value = {...value}
  // form.value.time = [timeTurn(form.value.taskEndTime), timeTurn(form.value.taskStartTime)]
  // // form.value.taskEndTime = timeTurn(form.value.taskEndTime);
  // // form.value.taskStartTime = timeTurn(form.value.taskStartTime);
  // form.value.isPublish = form.value.isPublish === 1;
  // console.log(777, form.value)
  imageDataUrl.value = value
}, {deep: true})


const radian = ref(false);
const previewHtml: Ref<string> = ref('');

const realTime = (e: any) => {
  previewHtml.value = e.html;
};
const rotateLeft = () => {
  if (cropper.value) {
    cropper.value.rotateLeft();
    updateImageData();
  }
}
const rotateRight = () => {
  if (cropper.value) {
    cropper.value.rotateRight();
    updateImageData();
  }
}
// 更新 imageDataUrl
const updateImageData = () => {
  if (!cropper.value) return;

  // 推荐方式 1：使用 getCropBlob()
  cropper.value.getCropBlob((blob: Blob) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = () => {
      imageDataUrl.value = reader.result as string; // 更新图片数据
    };
  }, 'image/png'); // 可选参数，指定图片格式

  // 方式 2：使用 getCropData()（但有时旋转信息丢失）
  // cropper.value.getCropData((data: string) => {
  //   imageDataUrl.value = data;
  // });
};
const DownImg = () => {
  if (!cropper.value) return;

  const aLink = document.createElement('a');
  aLink.download = Date.now().toString();

  cropper.value.getCropData((data: string) => {
    const img = new Image();
    img.src = data;

    img.onload = function () {
      const originalWidth = img.width;
      const originalHeight = img.height;

      if (radian.value) {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = option.value.full ? originalWidth : cropper.value.cropW;
        canvas.height = option.value.full ? originalHeight : cropper.value.cropH;
        ctx?.beginPath();
        ctx?.ellipse(
            canvas.width / 2,
            canvas.height / 2,
            canvas.width / 2,
            canvas.height / 2,
            0,
            0,
            Math.PI * 2
        );
        ctx?.clip();
        ctx?.drawImage(img, 0, 0, canvas.width, canvas.height);
        aLink.href = canvas.toDataURL('image/png');
        aLink.click();
      } else {
        aLink.href = data;
        aLink.click();
      }
    };
  });
};

const correct = () => {
  if (!cropper.value) return;
  const size = Math.min(cropper.value.cropW, cropper.value.cropH);
  cropper.value.cropW = size;
  cropper.value.cropH = size;
};

const arcChange = () => {
  radian.value = !radian.value;
};

const onFileChange = (e: Event) => {
  const input = e.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    const reader = new FileReader();
    reader.onload = (event) => {
      imageDataUrl.value = event.target?.result as string;
    };
    reader.readAsDataURL(input.files[0]);
  }
};

const submit = () => {
  if (cropper.value) {
    // 使用 getCropBlob 获取裁剪后的图片
    cropper.value.getCropBlob((blob: Blob) => {
      const reader = new FileReader();
      reader.onload = () => {
        const croppedImage = reader.result as string;
        emit('changeSubmitImg', croppedImage); // 传递裁剪后的图片数据
      };
      reader.readAsDataURL(blob); // 将 Blob 转为 DataURL
    }, 'image/png'); // 可选的图片格式
  }
};

const cancel = () => {
  emit('changeDialogVisible', false);
}
</script>

<style scoped>
.box {
  .crop {
    width: 100%;
    height: 500px;
    display: grid;
    grid-template-columns: 1fr 300px;
    grid-gap: 10px;
    padding: 10px;

    .cropper {
      width: 100%;
      height: 100%;
      background-color: #cccccc2e;
      border: 1px solid #cccccc4d;
    }

    .tool {
      width: 100%;
    }

    .view {
      width: 100%;
      height: 400px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      gap: 20px;

      .img-preview {
        width: 300px;
        height: 300px;
        overflow: auto;
        background-color: #cccccc2e;
        border: 1px solid #cccccc4d;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .radian {
        :deep(.show-preview) {
          border-radius: 50%;
        }
      }

      .btn {
        width: 100%;
        display: flex;
        justify-content: center;
        gap: 10px;

        .item {
          height: 32px;
          width: 32px;
          margin: 0;
          font-size: 20px;
          box-shadow: 0px 0px 2px white;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;
          color: white;
          transition: all 0.5s;

          &:nth-child(1) {
            background-color: #1961fe;
          }

          &:nth-child(2) {
            background-color: #b0a8b9;
          }

          &:hover {
            opacity: 0.8;
          }
        }
      }
    }
  }

  .tool {
    padding: 10px;
  }
}
</style>
